package server;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author junbao
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端⼝号*/
    private int port = 8080;

    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    private ServerMapper serverMapper = new ServerMapper();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void start() throws Exception {

        // 加载解析相关配置 web.xml
        // loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("-->Minicat start on port:" + port);

        /**
         * // 1.0版本
         * // 浏览器请求http://localhost:8080.返回一个固定字符串
        while(true) {
            Socket socket = serverSocket.accept();
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello, Minicat!";
            String response = HttpProtocolUtil.getHttpHeader200((data.getBytes().length)) + data;
            outputStream.write(response.getBytes());
            socket.close();
        }*/

        /**
         * // 2.0版本
         * // 封装request和response对象，返回html静态资源文件
        while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            // 封装对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();
        }
         */

        /**
         * // 3.0版本
         * // 可以请求动态资源（Servlet）
         *
        while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            // 封装对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else {
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        }
         */

        /**
        // 多线程版本
        // 不使用线程池
//        while(true) {
//            Socket socket = serverSocket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
//            requestProcessor.run();
//        }

        System.out.println("-->使用线程池进行多线程改造");
        // 使用线程池
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            //requestProcessor.run();
            threadPoolExecutor.execute(requestProcessor);
        }
         */


        while(true) {
            Socket socket = serverSocket.accept();
            //loadServlet();
            RequestProcessor requestProcessor = new RequestProcessor(socket, this.serverMapper);
            //requestProcessor.run();
            threadPoolExecutor.execute(requestProcessor);
            //socket.close();
        }
    }

    public void initMinicat() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> list = rootElement.selectNodes("//Service");
            for (int i = 0; i < list.size(); i++) {
                Element element = list.get(i);

                Element connectorElement = (Element) element.selectSingleNode("Connector");
                int port = Integer.valueOf(connectorElement.attributeValue("port"));
                this.port = port;

                Element engineElement = (Element) element.selectSingleNode("Engine");
                Element hostElement = (Element) engineElement.selectSingleNode("Host");
                String name = hostElement.attributeValue("name");
                this.serverMapper.setHostName(name);
                String appBase = hostElement.attributeValue("appBase");
                this.serverMapper.setWebappPath(appBase);
            }

            File file = new File(this.serverMapper.getWebappPath());
            List<String> projectList = new ArrayList<>();
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                File project = fileList[i];
                if(project.isDirectory()) {
                    projectList.add(project.getName());
                }
            }
            this.serverMapper.setProjectList(projectList);

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private void loadServlet() throws IOException {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> list = rootElement.selectNodes("//servlet");
            for (int i = 0; i < list.size(); i++) {
                Element element =  list.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat 的程序启动⼊⼝
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 初始化Minicat, 加载解析server.xml
            bootstrap.initMinicat();
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
